#!/usr/bin/python
import unittest
from StringIO import StringIO
import sys
import os

from uya.routerconf.configmod import misc

class TestMiscLibrary(unittest.TestCase):        
    def setUp(self):
        pass

    def test_struct(self):
        struct = misc.Struct(var1=1, var2=2)
        self.assertEqual(1, struct.var1)
        self.assertEqual(2, struct.var2)
        self.assertRaises(AttributeError, lambda: struct.var3)
        struct.var1 = 11
        self.assertEqual(11, struct.var1)
                
    def test_partial_function(self):
        def function(a, b):
            return a + b
        function1 = misc.partial_function(function, 1)
        self.assertEqual(3, function1(2))

    def test_flatten(self):
        lst = [[1, 2], [3, 4, 5], [6]] 
        self.assertEqual(range(1, 6+1), misc.flatten(lst))
                             
    def test_first(self):
        lst = [1, 2, 3, 4]
        self.assertEqual(1, misc.first(lst))
        self.assertEqual(1, misc.first(iter(lst)))
        self.assertEqual(None, misc.first([]))

    def test_itrue(self):
        lst = [0, None, 1, "", "2", (), [], [3]]
        self.assertEqual([1, "2", [3]], list(misc.itrue(lst)))        

    def test_debug(self):
        misc.verbose_level = 1
        fd = StringIO()
        misc.debug(0, "debug0", fd)
        self.assertEqual("debug0\n", fd.getvalue())
        fd = StringIO()
        misc.debug(1, "debug1", fd)
        self.assertEqual("debug1\n", fd.getvalue())
        fd = StringIO()
        misc.debug(2, "debug2", fd)
        self.assertEqual("", fd.getvalue())
                                    
    def test_run(self):
        text = "hola"
        command = ["echo", text]
        returncode, output, error = misc.run(command)
        self.assertEqual(0, returncode) 
        self.assertEqual(text, output.strip()) 

    def test_uniq(self):
        lst = [1, 2, 2, 1, 3, 3, 4, 5, 5, 5, 3]
        self.assertEqual([1, 2, 3, 4, 5], list(misc.uniq(lst)))

def suite():
    return unittest.TestLoader().loadTestsFromTestCase(TestMiscLibrary)
                 
if __name__ == '__main__':
    unittest.main(testRunner=unittest.TextTestRunner(verbosity=2))
